package com.rephilo.user.service;

import com.rephilo.api.code.CodeService;
import com.rephilo.user.dao.UserRepository;
import com.rephilo.user.model.User;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import java.util.Optional;
import java.util.UUID;

/**
 * user服务
 *
 * @author rephilo
 */
@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    @Reference
    private CodeService codeRemoteService;

    /**
     * 根据token查询user信息
     *
     * @param token
     * @return
     */
    public User getUserByToken(String token) {
        User user = new User();
        user.setToken(token);
        Optional<User> one = userRepository.findOne(Example.of(user));
        return one.orElse(new User());
    }

    /**
     * 根据email查询user信息
     *
     * @param email
     * @return
     */
    public User getUserByEmail(String email) {
        User user = new User();
        user.setEmail(email);
        Optional<User> one = userRepository.findOne(Example.of(user));
        return one.orElse(null);
    }

    /**
     * 注册接口
     *
     * @param email
     * @param password
     * @param code
     * @return
     */
    public Boolean register(String email, String password, String code) {
        Boolean flag = false;
        //校验验证码是否正确
        Integer validate = codeRemoteService.validate(email, code);
        if (validate.equals(0)) {
            flag = true;
        }
        //校验成功则入库
        if (flag) {
            User user = new User();
            user.setEmail(email);
            user.setPassword(password);
            userRepository.save(user);
        }

        return true;
    }

    /**
     * 登陆校验
     *
     * @param email
     * @param password
     * @return
     */
    public String login(String email, String password) {
        User user = new User();
        user.setEmail(email);
        user.setPassword(password);
        Optional<User> one = userRepository.findOne(Example.of(user));
        if (one.isPresent()) {
            String token = UUID.randomUUID().toString();
            User save = one.get();
            save.setToken(token);
            userRepository.save(save);

            return token;
        }

        return null;
    }
}
